<template>
    <van-nav-bar title="我的" style="border-bottom:1px solid black"/>

    <div class="Box">
        <div class="InfoBox">
            <div class="userImage">
<!--            <img src="../images/firstStep.png" style="width:50px;height:50px"/>-->

                <img :src="data.img_src" style="width:50px;height:50px"/>
        </div>
            <div class="userInfo">
            <div>用户名:{{data.userInfo.name}}</div>
            <div>工号:{{data.userInfo.ID}}</div>
            <div>手机号:{{data.userInfo.phone}}</div>
        </div>
            <div style="clear:both"></div>
        </div>
        <div class="underBox">
            <div class="menu">
                <div class="item" v-for="index in data.list" @click="get(index.name)">{{index.name}}</div>
            </div>
            <div class="exit">
                <div @click="quit">退出</div>
            </div>
        </div>
    </div>
    <el-dialog v-model="data.dialogFormVisible" title="Shipping address" width="80%">
        <el-form :model="data.form">
            <el-form-item>
                <a>消息内容</a>
                <el-input
                    v-model="data.form.message"
                    :rows="2"
                    type="textarea"
                    placeholder="Please input"
                />
            </el-form-item>

            <el-form-item label="收件人" >
                <el-select
                    v-model="value4"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip

                    :max-collapse-tags="3"
                    placeholder="Select"
                    style="width: 240px"
                >
                    <el-option
                        v-for="item in data.workers"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
<!--                    <el-option-->
<!--                        v-for="item in form.workers.user"-->
<!--                        :key="item.id"-->
<!--                        :label="item.id"-->
<!--                        :value="item.name"-->
<!--                    />-->
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="print()">
          Confirm
        </el-button>
      </span>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogTableVisible" title="所有消息" :width="data.width">
        <el-table :data="data.messages">
            <el-table-column property="send_time" label="发布日期"  :width="data.width/4"/>
            <el-table-column property="sender" label="发起人"  :width="data.width/4"/>
            <el-table-column property="message" label="消息内容" :width="data.width*2/4"/>
        </el-table>
    </el-dialog>
    <!--92 80 100-->
</template>

<script setup>
import { showDialog } from 'vant';
import {onMounted, reactive, ref} from 'vue';
import {useStore} from "vuex";
import {useRouter} from "vue-router";

const router = useRouter()
const store = useStore()

const value4 = ref([])
const dialogTableVisible = ref(false)
const data = reactive({
    userInfo:{},
    list:['发布消息'],
    dialogFormVisible:false,
    dialogTableVisible:false,
    form:{
        name:'',
        message: '',
        receiver:[],
        workers:[],
        date1: '',
        date2: ''
    },
    workers : [
        {
            id: '0001',
            name: '张三',
        },
        {
            id: '0002',
            name: '李四',
        }
    ],
    messages:[],
    works:[],
    width:'',
    img_src:'https://img0.baidu.com/it/u=4060770951,4069855872&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
})


onMounted(()=>{
    console.log('MinePage - mounted')
    // console.log(store.state.currentUser)

    /*vuex从本地读出来的数据是个序列化后的字符串，我们在这儿对它进行反序列化
    * 如果本地数据为空时，反序列化会触发异常，需要捕获异常
    * 反序列化：messages，works，permission
    * */
    getUserInfo()

    //加载用户权限，里面包括菜单列表，从而实现动态菜单的加载
    getPermissions()

    //配置发布消息所需的可接受消息用户列表
    getWorkers()

    //加载所有消息
    getMessages()

    // console.log(window.innerWidth*0.8)
    data.width = window.innerWidth*0.8
})
function getUserInfo(){
    let xx = store.state.currentUser
    // console.log('xx',xx)
    if((typeof xx) === "string"){
        xx.role = JSON.parse(xx.role)
    }
    let user = {
        name:xx.name,
        ID:xx.ID,
        phone:xx.phone,
        role:xx.role
    }
    data.userInfo = user
}
function getPermissions(){
    // console.log('mine permission ',typeof store.state.currentUser.permission)
    if((typeof store.state.currentUser.permission) === "string"){
        data.list = JSON.parse(store.state.currentUser.permission)
    }
    else{
        data.list = store.state.currentUser.permission
    }

    // console.log('lists: ',data.list)
}


function getWorkers(){
    let workers = []
    //从用户列表里排除自己的角色，因为消息是发给其他人的
    store.state.userList.filter((e)=>{
        if(e.role !== store.state.currentUser.role){
            // console.log(e.user)
            workers.push(e.user)
            return true
        }
    })
    // console.log('workers',workers)
    //获得工人列表

    //通过两次遍历获取工人可直接使用的数据
    let receiver = []
    workers.forEach((x)=>{
        // console.log(x)
        x.forEach((y)=>{
            // console.log('y',y)
            receiver.push(y)
        })
    })
    // console.log(receiver)

    //将整理出来的可接受消息的用户信息，保存到data/workers里，UI按照这个加载select选项
    data.workers = receiver
}

function getMessages(){
    //vuex默认加载本地消息，数据类型是序列化后的字符串
    //我们进行反序列化得到原始消息数据，把它存会到vuex，方便发布消息
    try{
        //反序列化后的数据保存在当前页面
        data.messages = JSON.parse(store.state.messages)
        // console.log('data.messages',data.messages)
        //反序列化后的数据保存到state，只要这样我们后面才能push新的message
        store.state.messages = data.messages
    }catch (error) {
        // console.log('err-messageParseEror')
        data.messages = store.state.messages
    }

    // console.log(data.userInfo)
    // console.log(store.state.messages)

    data.messages.filter((m)=>{
        // console.log(m.receiver)
        if(m.receiver.indexOf(data.userInfo.ID) !== -1){
            // console.log('yes')
            return true
        }
        else{
            // console.log('no')
            return false
        }
    })
    // console.log(data.messages)
}
function quit(){
    //调用vuex里的退出登录函数，清楚状态变量
    store.commit('quitLogin')
    //跳转到登陆页面
    router.replace({name:'Login'})
}

//菜单关联的函数，里面实现每个子菜单功能的触发
function get(x){
    // console.log(x)
    data.form.name = x
    if(x  === '发布消息'){
        // this.$router.push({name:'SendMessage'})
        //触发发布消息弹窗
        data.dialogFormVisible = true
    }
    else if(x === '我的消息'){
        //触发查看消息弹窗
        // data.dialogTableVisible = true
        // console.log(store.state.messages)
        this.dialogTableVisible = true
        window.requestAnimationFrame(()=>{})
    }
    else if(x === '我的职位'){
        // console.log('workNumber',store.state.currentUser.work)
        // console.log('workList',store.state.workList)

        //调用函数获取工人的信息
        let workDetail = getWorkDetail()

        //消息组件，显示我的职务信息
        showDialog({
            title: x,
            message: workDetail
        }).then(() => {
            // on close
        });
    }

}
function getWorkDetail(){
    // console.log('vuex - currentUser:',store.state.currentUser)
    //定义一个字符串变量，里面拼接一下消息内容，我的角色，我的职位和我的职务
    let current = store.state.currentUser

    if((typeof current.role) === "string"){
        // console.log('is string')
        // console.log(JSON.parse(current.role))
        data.userInfo.role = JSON.parse(current.role)
    }
    else{
        data.userInfo.role = current.role
    }
    if((typeof current.work) === "string"){
        console.log('is string')
        // console.log(JSON.parse(current.role))
        data.userInfo.work = JSON.parse(current.work)
    }
    else{
        data.userInfo.work = current.work
    }
    // console.log('role',data.userInfo.role)

    // console.log('data.userInfo',data.userInfo)

    // 拼接角色
    let workDetail = '我的角色:';
    data.userInfo.role.forEach((x)=>{
        // console.log(x)
        workDetail += ' ' +x.name;
    })
    workDetail += '\n';

    // 拼接职位
    workDetail +='我的职位：'
    data.userInfo.work.forEach((r)=>{
        // console.log(r)
        workDetail += ' ' + r.address
    })
    workDetail += '\n' + '我的职务：'
    let n = 1
    data.userInfo.work.forEach((r)=>{
        workDetail += n + '. ' + r.detail+' ';
        n += 1
    })

    // console.log('workDetail',workDetail)
    return workDetail
}

//发布消息
function print(){
    // console.log('ok')
    // console.log(data.userInfo)
    // console.log(value4._rawValue)
    //console.log(formateDate(new Date()))
    let message = {send_time:formateDate(new Date()),sender:data.userInfo.ID,message:data.form.message,receiver:value4._rawValue}
    // console.log(message)
    /*
    * messages新从本地读出来时是个字符串，我们把它格式化成json，然后给state存回去，此操作在生命周期函数里完成
    * 它才能commit新的message
    * */
    store.commit("SendMessage",message)
    data.messages = store.state.messages
    data.dialogFormVisible = false
}
function formateDate(datetime) {
        function addDateZero(num) {
            return (num < 10 ? '0' + num : num)
        }
        const d = new Date(datetime)
        const formatdatetime = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate()) + ' ' + addDateZero(d.getHours()) + ':' + addDateZero(d.getMinutes()) + ':' + addDateZero(d.getSeconds())
        const formatdate = d.getFullYear() + '-' + addDateZero(d.getMonth() + 1) + '-' + addDateZero(d.getDate())
    return formatdate
}

</script>

<style scoped>
.InfoBox{
    background-color:white;
    height:70px;
    border:1px solid black;
    border-radius:10px;

    display:flex;
    flex-direction: row;
    align-items:center;
}
.InfoBox .userImage{
    border:1px solid black;
    height:50px;
    width:50px;
    border-radius:50px;
    margin-left:10px;
    float:left;

    display:inline-block;
}
.InfoBox .userInfo{
    /*border:1px solid black;*/
    height:50px;
    width:200px;
    float:left;
    margin-left:10px;

    display:inline-block;

    font-size:13px;
}
.Box{
    /*background-color:#E0FFFF;*/
    background-color: #f2f3f3;
}
.Box .underBox{
    height:calc(100vh - 162px);

    display:flex;
    flex-direction: column;
    justify-content: space-between;
    align-items:center;
}
.Box .underBox .menu{
    width:100%;
}
.Box .underBox .menu .item{
    background-color:white;
    margin-top:10px;
    text-align:center;
    line-height:50px;
}
.Box .underBox .exit{
    height:40px;
    width:60%;
    border-radius:10px;

    text-align:center;
    line-height:40px;

    background-color:#ff3c3cbd;
    margin-bottom: 15px;
}
</style>